package com.company.zonghelizi.jihe.myjihe;

/**
 * 双向链表实现
 * 单项链表
 */
public class MyLinkedList {
    private Node fistNode = null;
    private int size = 0;

    public void addFirst(Object obj){
        Node node = new Node();
        node.setObj(obj);
        node.setNext(fistNode);
        fistNode = node;
        size++;
    }

    // 删除首元素
    public void removeFirst(){
        Node second = fistNode.getNext();
        fistNode.setNext(null);
        fistNode = second;
        size--;
    }

    public Object get(int index){
        if(index<0||index>=size){
            throw new IndexOutOfBoundsException("index="+index);
        }
        Node node = fistNode;
        for (int i = 0; i < index; i++) {
            node = node.getNext();
        }

        return node.getObj();
    }

    // 将obj插入到index
    public void add(int index,Object obj){
        if(index<0||index>=size){
            throw new IndexOutOfBoundsException("index="+index);
        }
        // 新node
        Node newnode = new Node();
        // index上一个node
        Node prenode = fistNode;
        for (int i = 0; i < index-1; i++) {
            prenode = prenode.getNext();
        }
        // index-1处node
        Node node = prenode.getNext();
        prenode.setNext(newnode);
        newnode.setObj(obj);
        newnode.setNext(node);
        size++;
    }

    // 删除index
    public void remove(int index){
        if(index<0||index>=size){
            throw new IndexOutOfBoundsException("index="+index);
        }
        // 新node
        Node newnode = new Node();
        // index上一个node
        Node prenode = fistNode;
        for (int i = 0; i < index-1; i++) {
            prenode = prenode.getNext();
        }
        prenode.setNext(prenode.getNext().getNext());
        size--;
    }
}

class Node{
    private Object obj;
    private Node next;

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "obj=" + obj +
                ", next=" + next +
                '}';
    }
}